<?php
if (!defined('BASEPATH')) exit('No direct script access allowed');
require_once (APPPATH.'libraries/branchobject.php');

/**
 * Branch Model
 */
class Branch_Model extends CI_Model
{
	private static $_instance;
	
	function __construct()
	{
		parent::__construct();
		self::$_instance =& $this;
	}
	
	public static function getInstance()
	{
		if (self::$_instance == NULL)
			self::$_instance = new Branch_Model();
		return self::$_instance;
	}
	
	public function getAllBranches()
	{
		$branches = array();
		
		$data = $this->db->get(BRANCHES_TABLE);
		
		foreach ($data->result() as $row)
		{
			$branches[] = new BranchObject($row->id, $row->name);
		}
		
		return $branches;
	}
	
	public function getBranchById($id)
	{
		$branch = new BranchObject();
		
		$this->db->where('id', $id);
		$data = $this->db->get(BRANCHES_TABLE);
		
		if ($data->num_rows() > 0)
		{
			$row = $data->row();
			$branch->setId($row->id);
			$branch->setName($row->name);
		}
		
		return $branch;
	}
	
	public function insertBranch($branch)
	{
		$query = "INSERT INTO ".BRANCHES_TABLE." VALUES (NULL, ?)";
		
		$this->db->trans_start();
		$this->db->query($query, array($branch->getName()));
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE)
			return INSERT_ERROR;
		
		return ERROR_NONE;
	}
	
	public function updateBranch($id, $branch)
	{
		$query = "UPDATE ".BRANCHES_TABLE." SET name=? WHERE id=?";
		
		$this->db->trans_start();
		$this->db->query($query, array($branch->getName(), $id));
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE)
			return UPDATE_ERROR;
		
		return NONE_ERROR;
	}
	
	public function deleteBranchById($id)
	{
		$this->db->trans_start();
		$this->db->where('id', $id);
		$this->db->delete(BRANCHES_TABLE);
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE)
			return DELETE_ERROR;
		
		return NONE_ERROR;
	}
	
	public function deleteMultipleBranches($ids)
	{
		$query = "";
		$size = count($ids);
		$query = "DELETE FROM ".BRANCHES_TABLE." WHERE id IN (";
		
		for($i = 0; $i < ($size - 1); $i++)
		{
			$query .= "?, ";
		}
		
		$query .= "?)";
		
		$this->db->trans_start();
		$this->db->query($query, $ids);
		$this->db->trans_complete();
		
		if ($this->db->trans_status() === FALSE)
			return DELETE_ERROR;
		
		return ERROR_NONE;
	}
	
	public function isBranchExisted_id($id)
	{
		$this->db->where('id', $id);
		$data = $this->db->get(BRANCHES_TABLE);

		return ($data->num_rows() > 0);
	}
	
	public function findBranch($name)
	{
		$id = -1;
		
		$query = "SELECT id FROM " . BRANCHES_TABLE . " WHERE name LIKE N'%" . $this->db->escape_like_str($name) . "%'";
		$data = $this->db->query($query);
		
		if ($data->num_rows() > 0)
		{
			$row = $data->row();
			$id = $row->id;
		}

		return $id;
	}
}


?>